package com.exp.zhiwendemo;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import com.dnake.v710.MessageLayer;
import com.dnake.v710.dmsg;
import com.dnake.v710.dxml;
import com.dnake.v710.sys;
import com.exp.zhiwendemo.widget.Button2;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

public class SetupLabel extends Activity {
	private RelativeLayout layout_common, layout_device, layout_network, layout_voip;
	private Button2 btn_common, btn_device, btn_network, btn_voip;
	private SeekBar mVolume;

	public static SetupLabel handler = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setup);
		
		Button2 btn;

		handler = this;
		// 常用按钮以及常用界面
		btn_common = (Button2) this.findViewById(R.id.setup_btn_common);
		btn_common.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadMenu();
				loadCommon();
			}
		});
		layout_common = (RelativeLayout) this.findViewById(R.id.setup_layout_common);
		mVolume = (SeekBar) this.findViewById(R.id.setup_volume_bar);
		mVolume.setMax(sys.volume.MAX);
		
		btn = (Button2) this.findViewById(R.id.setup_common_ok);
		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				sys.volume.talk = sys.volume.MAX - mVolume.getProgress();
				sys.save();
			}
		});
		
		// 设备编号按钮以及编号设置界面
		btn_device = (Button2) this.findViewById(R.id.setup_btn_device);
		btn_device.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				loadMenu();
				loadDevice();
			}
		});

		layout_device = (RelativeLayout) this.findViewById(R.id.setup_layout_device);
		
		btn = (Button2) this.findViewById(R.id.setup_device_ok);
		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText edit;
				int host, slave;
				
				edit = (EditText)findViewById(R.id.setup_host_edit);
				host = Integer.parseInt(edit.getText().toString());
				
				edit = (EditText)findViewById(R.id.setup_slave_edit);
				slave = Integer.parseInt(edit.getText().toString());
				
				MessageLayer.setId(host, slave);
			}
		});
			
		// 网络设置按钮以及网络设置界面
		btn_network = (Button2) this.findViewById(R.id.setup_btn_lan);
		btn_network.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				loadMenu();
				loadNetwork();
			}
		});
		
		layout_network = (RelativeLayout) this.findViewById(R.id.setup_layout_network);
		CheckBox c = (CheckBox)this.findViewById(R.id.setup_network_dhcp);
		c.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText e = (EditText) findViewById(R.id.setup_network_ip);
				EditText e2 = (EditText) findViewById(R.id.setup_network_mask);
				EditText e3 = (EditText) findViewById(R.id.setup_network_gateway);
				EditText e4 = (EditText) findViewById(R.id.setup_network_dns);
				CheckBox c = (CheckBox) findViewById(R.id.setup_network_dhcp);
				if (c.isChecked()) {
					e.setEnabled(false);
					e2.setEnabled(false);
					e3.setEnabled(false);
					e4.setEnabled(false);
				} else {
					e.setEnabled(true);
					e2.setEnabled(true);
					e3.setEnabled(true);
					e4.setEnabled(true);
				}
			}
		});
		btn = (Button2) this.findViewById(R.id.setup_network_ok);
		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText e = (EditText) findViewById(R.id.setup_network_ip);
				EditText e2 = (EditText) findViewById(R.id.setup_network_mask);
				EditText e3 = (EditText) findViewById(R.id.setup_network_gateway);
				EditText e4 = (EditText) findViewById(R.id.setup_network_dns);
				EditText e5 = (EditText) findViewById(R.id.setup_network_server);
				CheckBox c = (CheckBox) findViewById(R.id.setup_network_dhcp);

				String ip = e.getText().toString();
				String mask = e2.getText().toString();
				String gateway = e3.getText().toString();
				String dns = e4.getText().toString();
				String server = e5.getText().toString();

				if (ipValidate(ip) && ipValidate(mask) && ipValidate(gateway) && ipValidate(server) && ipMatch(ip, mask, gateway)) {
					dxml p = new dxml();
					dmsg req = new dmsg();
					p.setInt("/params/dhcp", c.isChecked() ? 1 : 0);
					p.setText("/params/ip", ip);
					p.setText("/params/mask", mask);
					p.setText("/params/gateway", gateway);
					p.setText("/params/dns", dns);
					req.to("/settings/lan/setup", p.toString());
					
					sys.talk.server = new String(server);
					sys.save();
				} 
			}
		});		
		
		// VOIP设置
		btn_voip = (Button2) this.findViewById(R.id.setup_btn_voip);
		btn_voip.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				loadMenu();
				loadVoip();
			}
		});
		
		layout_voip = (RelativeLayout) this.findViewById(R.id.setup_layout_voip);
		btn = (Button2) findViewById(R.id.setup_voip_ok);
		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText e = (EditText) findViewById(R.id.setup_voip_proxy);
				String s = e.getText().toString();
				if (s.indexOf("sip:") == -1) {
					s = "sip:" + s;
					e.setText(s);
				}
				sys.sip.proxy = new String(s);
				e = (EditText) findViewById(R.id.setup_void_realm);
				sys.sip.realm = new String(e.getText().toString());
				e = (EditText) findViewById(R.id.setup_voip_passwd);
				sys.sip.passwd = new String(e.getText().toString());
				e = (EditText) findViewById(R.id.setup_voip_user);
				sys.sip.user = new String(e.getText().toString());
				e = (EditText) findViewById(R.id.setup_stun_ip);
				sys.sip.stun.ip = new String(e.getText().toString());
				e = (EditText) findViewById(R.id.setup_stun_port);
				sys.sip.stun.port = Integer.valueOf(e.getText().toString());
				CheckBox c = (CheckBox) findViewById(R.id.setup_voip_enable);
				sys.sip.enable = c.isChecked() ? 1 : 0;
				
				sys.save();
			}
		});
		
		loadMenu();
		loadCommon();
	}

	private void loadMenu() {
		btn_common.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.setup_btn_common));
		btn_device.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.setup_btn_common));
		btn_voip.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.setup_btn_common));
		btn_network.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.setup_btn_common));
		layout_common.setVisibility(RelativeLayout.GONE);
		layout_device.setVisibility(RelativeLayout.GONE);
		layout_network.setVisibility(RelativeLayout.GONE);
		layout_voip.setVisibility(RelativeLayout.GONE);
	}
	
	private void loadCommon() {
		mVolume.setProgress(sys.volume.MAX-sys.volume.talk);
		btn_common.setBackgroundDrawable(getResources().getDrawable(R.drawable.setup_btn_common2));
		layout_common.setVisibility(RelativeLayout.VISIBLE);
	}
	
	private void loadDevice() {
		int host = (sys.talk.building%100)*100+sys.talk.unit;
		int slave = sys.talk.floor*100+sys.talk.family;
		
		EditText edit = (EditText) this.findViewById(R.id.setup_host_edit);
		edit.setText(""+host);
	
		edit = (EditText) this.findViewById(R.id.setup_slave_edit);
		edit.setText(""+slave);	
		
		btn_device.setBackgroundDrawable(getResources().getDrawable(R.drawable.setup_btn_common2));
		layout_device.setVisibility(RelativeLayout.VISIBLE);
	}
	
	public String getLocalIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = (NetworkInterface) en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress())
						return inetAddress.getHostAddress().toString();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getLocalMac() {
		String mac_s = "";
		try {
			NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIp()));
			if (ne != null) {
				byte[] mac = ne.getHardwareAddress();
				if (mac != null)
					mac_s = String.format("%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mac_s;
	}
	
	private void loadNetwork() {
		dmsg req = new dmsg();
		dxml p = new dxml();
		int dhcp;
		
		req.to("/settings/lan/query", null);
		p.parse(req.mBody);
		dhcp = p.getInt("/params/dhcp", 0);
		
		CheckBox c = (CheckBox)findViewById(R.id.setup_network_dhcp);
		
		EditText e = (EditText) findViewById(R.id.setup_network_ip);
		e.setText(p.getText("/params/ip"));
		e.setInputType(InputType.TYPE_CLASS_TEXT);
		EditText e2 = (EditText) findViewById(R.id.setup_network_mask);
		e2.setText(p.getText("/params/mask"));
		e2.setInputType(InputType.TYPE_CLASS_TEXT);
		EditText e3 = (EditText) findViewById(R.id.setup_network_gateway);
		e3.setText(p.getText("/params/gateway"));
		e3.setInputType(InputType.TYPE_CLASS_TEXT);
		EditText e4 = (EditText) findViewById(R.id.setup_network_dns);
		e4.setText(p.getText("/params/dns"));
		e4.setInputType(InputType.TYPE_CLASS_TEXT);
		EditText e5 = (EditText) findViewById(R.id.setup_network_server);
		e5.setText(sys.talk.server);
		e5.setInputType(InputType.TYPE_CLASS_TEXT);
		
		TextView tv = (TextView) findViewById(R.id.setup_network_real);
		String ip = getLocalIp();
		if (ip != null)
			tv.setText(ip);
		else
			tv.setText("");
		
		tv = (TextView) findViewById(R.id.setup_network_mac);
		String mac = getLocalMac();
		if (mac != null)
			tv.setText(mac);
		else
			tv.setText("");
		
		if (dhcp == 0) {
			c.setChecked(false);
			e.setEnabled(true);
			e2.setEnabled(true);
			e3.setEnabled(true);
			e4.setEnabled(true);
		} else {
			c.setChecked(true);
			e.setEnabled(false);
			e2.setEnabled(false);
			e3.setEnabled(false);
			e4.setEnabled(false);
		}
		
		btn_network.setBackgroundDrawable(getResources().getDrawable(R.drawable.setup_btn_common2));
		layout_network.setVisibility(RelativeLayout.VISIBLE);
	}
	
	private void loadVoip() {
		btn_voip.setBackgroundDrawable(getResources().getDrawable(R.drawable.setup_btn_common2));
		layout_voip.setVisibility(RelativeLayout.VISIBLE);
		
		EditText e = (EditText) findViewById(R.id.setup_voip_proxy);
		e.setText(sys.sip.proxy);
		e = (EditText) findViewById(R.id.setup_void_realm);
		e.setText(sys.sip.realm);
		e = (EditText) findViewById(R.id.setup_voip_passwd);
		e.setText(sys.sip.passwd);
		e = (EditText) findViewById(R.id.setup_voip_user);
		e.setText(sys.sip.user);
		e = (EditText) findViewById(R.id.setup_stun_ip);
		e.setText(sys.sip.stun.ip);
		e = (EditText) findViewById(R.id.setup_stun_port);
		e.setText(String.valueOf(sys.sip.stun.port));
		CheckBox c = (CheckBox) findViewById(R.id.setup_voip_enable);
		c.setChecked(sys.sip.enable == 0 ? false : true);
	}
	
	private boolean ipValidate(String addr) {
		final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
		if (!addr.matches(REGX_IP))
			return false;
		return true;
	}
	
	private boolean ipMatch(String ip, String mask, String gateway) {
		try {
			byte [] _ip = InetAddress.getByName(ip).getAddress();
			byte [] _mask = InetAddress.getByName(mask).getAddress();
			byte [] _gateway = InetAddress.getByName(gateway).getAddress();
			for(int i=0; i<4; i++) {
				_ip[i] &= _mask[i];
				_gateway[i] &= _mask[i];
				if (_ip[i] != _gateway[i])
					return false;
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return true;
	}
	
}
